<template>
  <!-- 链接扫描 -->
  <div class="friend-link-container">
    <!-- 在新增按钮下方添加搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" class="search-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="搜索字段">
              <el-select v-model="selectedField" placeholder="请选择" clearable>
                <el-option v-for="field in searchFields" :key="field.value" :label="field.label" :value="field.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="搜索内容">
              <el-input v-model="searchQuery" placeholder="请输入搜索内容" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-button type="primary" plain @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
            <el-button type="success" plain @click="handleAdd">新增</el-button>

            <el-button type="warning" plain @click="handleScan">手动扫描</el-button>
            <el-button type="info" plain @click="handleScanTime">定制扫描策略</el-button>

          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table :data="filteredData" row-key="id" table-layout="auto" style="width: 100%">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="80" :index="indexMethod" />
      <el-table-column prop="name" label="链接名称" width="180" />
      <el-table-column prop="url" label="链接地址" show-overflow-tooltip width="200px" />
      <el-table-column prop="status" label="扫描状态" width="120">
        <template #default="{row}">
          <el-tag :type="row.status ? 'success' : 'danger'">
            {{ row.status ? '无异常' : '待验证' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="strategyName" label="策略名称" width="180">
        <template #default="{row}">
          <el-tag>
            <span v-if="row.strategyName == ''">未扫描</span>
            <span v-if="row.strategyName == '1'">手动扫描</span>
            <span v-if="row.strategyName == '2'">每周全面扫描</span>
            <span v-if="row.strategyName == '3'">每日快速扫描</span>
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="createTime" label="最后扫描时间" width="200" />
        <!-- <template #default="{row}">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column> -->
      <el-table-column prop="remark" label="备注" width="200" />

      <el-table-column label="操作" width="180">
        <template #default="{row}">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="info" size="small" @click="handleDelete(row.id)">隐藏</el-button>
          <el-button type="danger" size="small" @click="handleDelete(row.id)">下架</el-button>

        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size" :page-sizes="[10, 20, 30, 50]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper" @current-change="updateData" @size-change="handleSizeChange" style="margin-top: 20px;" />

    <!-- 弹窗 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '友链详情' : '新增友链'">
      <el-form ref="dataFormRef" :model="formData" label-width="100px" class="multi-column-form">
        <el-row :gutter="20">
          <!-- 第一行：链接名称 + 链接地址 -->
          <el-col :span="12">
            <el-form-item label="链接名称" prop="name">
              <el-input :disabled='!isButtonShow' v-model="formData.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="链接地址" prop="url">
              <el-input :disabled='!isButtonShow' v-model="formData.url"></el-input>
            </el-form-item>
          </el-col>

          <!-- 第二行：上架时间 + 策略名称 -->
          <el-col :span="12">
            <el-form-item label="上架时间" prop="linkFlag">
              <el-date-picker :disabled='!isButtonShow' v-model="formData.createTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择日期时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="策略名称" prop="strategyName" style="width: 320px">
              <el-select v-model="formData.strategyName" :disabled='!isButtonShow' placeholder="请选择扫描类型" clearable>
                <el-option label="手动扫描" value="1" />
                <el-option label="每周全面扫描" value="2" />
                <el-option label="每日快速扫描" value="3" />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 第三行：扫描状态 + 备注 -->
          <el-col :span="12">
            <el-form-item label="扫描状态" prop="status">
              <el-switch v-model="formData.status" inline-prompt :disabled='!isButtonShow' :active-value="1" :inactive-value="0" active-text="启动" inactive-text="禁用" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input :disabled='!isButtonShow' v-model="formData.remark" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div v-if="isButtonShow">
          <el-button @click="cancel()">取消</el-button>
          <el-button type="primary" @click="submit()">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 手动扫描弹窗 -->
    <el-dialog v-model="manualScanVisible" title="手动扫描" width="60%" :close-on-click-modal="false" custom-class="scan-dialog">
      <el-table :data="manualScanData" style="width: 100%">
        <el-table-column prop="name" label="链接名称" width="180" />
        <el-table-column prop="url" label="链接地址" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{row}">
            <el-tag :type="row.status ? 'success' : 'danger'">
              {{ row.status ? '启用' : '待验证' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="scanTime" label="扫描时间" width="200" />
      </el-table>

      <template #footer>
        <el-button @click="manualScanVisible = false">取消</el-button>
        <el-button type="primary" @click="manualScanVisible = false">确定</el-button>
      </template>
    </el-dialog>

    <!-- 定时策略扫描弹窗 -->
    <el-dialog v-model="manualScanTime" title="定制策略扫描" width="60%" :close-on-click-modal="false" custom-class="scan-dialog">
      <el-form ref="dataFormRef" :model="regularData" label-width="100px" class="multi-column-form">
        <el-row :gutter="20">
          <!-- 第一行：链接名称 + 链接地址 -->
          <el-col :span="12">
            <el-form-item label="策略名称" prop="policyName">
              <el-input v-model="regularData.policyName"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="策略内容" prop="content">
              <el-input v-model="formData.content" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="扫描类型" prop="scanType">
              <el-select style="width: 220px" v-model="regularData.scanType" placeholder="请选择扫描类型">
                <el-option label="快速扫描" value="1"></el-option>
                <el-option label="深度扫描" value="2"></el-option>
                <el-option label="全面扫描" value="3"></el-option>
                <el-option label="自定义扫描" value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="扫描频率" prop="timerSetting">
              <el-select style="width: 220px" v-model="regularData.timerSetting" placeholder="请选择扫描频率">
                <el-option label="仅一次" value="1"></el-option>
                <el-option label="每小时" value="2"></el-option>
                <el-option label="每天" value="3"></el-option>
                <el-option label="每周" value="4"></el-option>
                <el-option label="每月" value="5"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="失效阈值" prop="threshold">
                <el-input v-model="regularData.threshold"></el-input>
            </el-form-item>
          </el-col>

          <!-- 第二行：上架时间 + 策略名称 -->
          <el-col :span="12">
            <el-form-item label="时间段" prop="startTime">
              <el-date-picker v-model="regularData.startTime" type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" />
              <!-- <el-date-picker :disabled='!isButtonShow' v-model="regularData.startTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择日期时间">
              </el-date-picker> -->
            </el-form-item>
          </el-col>

          <!-- <el-col :span="12">
        <el-form-item label="策略状态" prop="strategyStatus">
          <el-switch
            v-model="regularData.strategyStatus"
            inline-prompt
            :active-value="1"
            :inactive-value="0"
            active-text="启动"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-col> -->
          <el-col :span="12">
            <el-form-item label="备注" prop="notes">
              <el-input v-model="regularData.notes" />
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="manualScanTime = false">取消</el-button>
        <el-button type="primary" @click="manualScanTimeSubmit()">确定</el-button>
      </template>
    </el-dialog>

    <!-- 弹窗 -->
    <el-dialog v-model="dialogScan" :title="扫描策略">
      <el-form ref="dataFormRef" :model="formData" label-width="100px" class="multi-column-form">
        <el-row :gutter="20">
          <!-- 第一行：链接名称 + 链接地址 -->
          <el-col :span="12">
            <el-form-item label="链接名称" prop="name">
              <el-input :disabled='!isButtonShow' v-model="formData.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="链接地址" prop="url">
              <el-input :disabled='!isButtonShow' v-model="formData.url"></el-input>
            </el-form-item>
          </el-col>

          <!-- 第二行：上架时间 + 策略名称 -->
          <el-col :span="12">
            <el-form-item label="上架时间" prop="linkFlag">
              <el-date-picker :disabled='!isButtonShow' v-model="formData.createTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择日期时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="策略名称" prop="strategyName">
              <el-input :disabled='!isButtonShow' v-model="formData.strategyName" />
            </el-form-item>
          </el-col>

          <!-- 第三行：扫描状态 + 备注 -->
          <el-col :span="12">
            <el-form-item label="扫描状态" prop="status">
              <el-switch v-model="formData.status" inline-prompt :disabled='!isButtonShow' :active-value="1" :inactive-value="0" active-text="启动" inactive-text="禁用" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input :disabled='!isButtonShow' v-model="formData.remark" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div v-if="isButtonShow">
          <el-button @click="cancel()">取消</el-button>
          <el-button type="primary" @click="submit()">确定</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

// 本地存储Key
const STORAGE_KEY = 'friend_links_data'
const STRATEGY_STORAGE_KEY = 'scan_strategies_data'

// 新增响应式数据
const searchFields = [
  { label: '链接名称', value: 'name' },
  { label: '链接地址', value: 'url' },
  { label: '策略名称', value: 'strategyName' },
  { label: '扫描状态', value: 'status' },
  { label: '最后扫描时间', value: 'createTime' },
  { label: '备注', value: 'remark' }
]

const formatDate = (dateString) => {
  return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss')
}

// 类型选项（前端模拟字典）
const typeOptions = {
  blog: '博客链接',
  partner: '合作伙伴',
  gov: '政府网站'
}
const indexMethod = (index) => {
  return index + 1;
}
//取消按钮
const cancel = () => {
  isEdit.value = false
  dialogVisible.value = false
}

//新增按钮
const submit = () => {
  // 表单验证
  if (!formData.value.name || !formData.value.url) {
    ElMessage.error('请填写链接名称和地址')
    return
  }




  // 如果是编辑模式
  if (isEdit.value) {
    const index = allData.value.findIndex(item => item.id === formData.value.id)
    if (index !== -1) {
      // 更新修改时间
      formData.value.updateTime = new Date().toISOString()
      // 替换原数据
      allData.value.splice(index, 1, formData.value)
      ElMessage.success('修改成功')
    }
  } else {
    // 新增模式 - 创建完整数据对象
    const newItem = {
      ...formData.value,
      id: Date.now(), // 生成唯一ID
      createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'), // 创建时间
      updateTime: '', // 新增时无更新时间
      status: formData.value.status // 默认启用状态
    }

    // 添加到数据列表开头
    allData.value.unshift(newItem)
    ElMessage.success('新增成功')
  }

  // 保存到本地存储
  saveToStorage()

  // 关闭弹窗
  dialogVisible.value = false
  isEdit.value = false
}

//新增定时扫描策略按钮
const manualScanTimeSubmit = () => {
  // 表单验证
  if (!regularData.value.policyName ||
    !regularData.value.scanType ||
    !regularData.value.timerSetting ||
    !regularData.value.startTime) {
    ElMessage.error('请填写完整的策略信息')
    return
  }
  const newStrategy = {
    ...regularData.value,
    id: Date.now() // 生成唯一ID
  }
  scanStrategies.value.unshift(newStrategy)
  ElMessage.success('策略添加成功')
  // 保存到本地存储
  saveScanStrategies()

  // 重置表单和状态
  manualScanTime.value = false
  isEditingStrategy.value = false
  regularData.value = {
    policyName: '',
    strategyStatus: '',
    scanType: '',
    scanDepth: '',
    timerSetting: '',
    startTime: '',
    notes: '',
    content: '',
    threshold:'',
  }
}

// 新增：保存定时策略数据
const saveScanStrategies = () => {
  try {
    localStorage.setItem(STRATEGY_STORAGE_KEY, JSON.stringify(scanStrategies.value))
  } catch (error) {
    console.error('定时策略保存失败:', error)
    ElMessage.error('定时策略保存失败')
  }
}

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表单数据
const formData = ref({
  id: null,
  name: '',
  url: '',
  linkFlag: 'blog',
  status: 1,
  sort: 0,
  createTime: '',
  updateTime: ''
})

//定时策略扫描表单数据
const regularData = ref({
  policyName: '',
  strategyStatus: '',
  scanType: '',
  scanDepth: '',
  timerSetting: '',
  startTime: ''
})

// 响应式数据
const allData = ref([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const searchQuery = ref('')
const selectedField = ref('')  // 默认搜索字段
const isButtonShow = ref(true)
const manualScanVisible = ref(false)
const dialogScan = ref(false)
const manualScanTime = ref(false)
const scanStrategies = ref([])

// 写死的手动扫描数据
const manualScanData = ref([
  {
    name: '微博公众号链接',
    url: 'https://weibo.com/',
    status: 1,
    scanTime: '2025.05.28 19:30:00'
  },
  {
    name: 'XXX',
    url: 'https://www.baidu.com/',
    status: 0,
    scanTime: '2025.05.28 19:30:00'
  },
  {
    name: 'XXX',
    url: 'https://www.baidu.com/',
    status: 0,
    scanTime: '2025.05.28 19:30:00'
  }
])
import { getTime } from '@/utils/myMethod' //工具类
//手动扫描时间
const handleScan = () => {
  //   manualScanVisible.value = true
  setTimeout(() => {
    allData.value = []
    const data1 = {
      id: Date.now() + 1,
      name: `百度`,
      url: `https://www.baidu.com/`,
      status: 1,
      strategyName: '1',
      createTime: getTime(new Date(), 'YMD'),
      remark: '链接扫描',
    }

    const data2 = {
      id: Date.now() + 2,
      name: `知网`,
      url: `https://kns.cnki.net/`,
      status: 1,
      strategyName: '1',
      createTime: getTime(new Date(), 'YMD'),
      remark: '链接扫描',
    }

    const data3 = {
      id: Date.now() + 3,
      name: `新浪微博`,
      url: `https://weibo.com/newlogin?tabtype=weibo&gid=102803&openLoginLayer=0&url=https%3A%2F%2Fweibo.com%2F`,
      status: 0,
      strategyName: '2',
      createTime: '2025-05-19',
      remark: '链接扫描',
    }

    allData.value.push(data1, data2, data3)
  }, 300)
}

//定时策略扫描
const handleScanTime = () => {
  manualScanTime.value = true
}



// 计算属性
const filteredData = computed(() => {
  // 原始数据过滤
  let filteredList = allData.value

  // 当有搜索条件时进行过滤
  if (searchQuery.value && selectedField.value) {
    filteredList = allData.value.filter(item => {
      const fieldValue = String(item[selectedField.value] || '')
      return fieldValue.toLowerCase().includes(searchQuery.value.toLowerCase())
    })
  }

  // 分页处理
  const start = (pagination.current - 1) * pagination.size
  return filteredList.slice(start, start + pagination.size)
})

// 生命周期钩子
onMounted(() => {
  console.log('初始数据:', allData.value)
  if (!Array.isArray(allData.value)) {
    allData.value = []
  }
  loadFromStorage()
})

// 搜索方法
const handleSearch = () => {
  if (!selectedField.value) {
    ElMessage.error('请选择搜索条件后查询')
    return
  }
  if (!searchQuery.value) {
    ElMessage.error('请输入搜索内容')
    return
  }
  pagination.current = 1  // 搜索后重置到第一页
}

// 重置方法
const handleReset = () => {
  selectedField.value = ''
  searchQuery.value = ''
  pagination.current = 1
}

// 数据操作方法
const loadFromStorage = () => {
  try {
    const saved = localStorage.getItem(STORAGE_KEY)
    // 双重验证：存在性检查和类型验证
    const parsedData = saved ? JSON.parse(saved) : []

    // 确保始终返回数组
    allData.value = []


    const data1 = {
      id: Date.now() + 1,
      name: `百度`,
      url: `https://www.baidu.com/`,
      status: 0,
      strategyName: '',
      createTime: '',
      remark: '链接扫描',
    }

    const data2 = {
      id: Date.now() + 2,
      name: `知网`,
      url: `https://kns.cnki.net/`,
      status: 0,
      strategyName: '',
      createTime: '',
      remark: '链接扫描',
    }

    const data3 = {
      id: Date.now() + 3,
      name: `新浪微博`,
      url: `https://weibo.com/newlogin?tabtype=weibo&gid=102803&openLoginLayer=0&url=https%3A%2F%2Fweibo.com%2F`,
      status: 0,
      strategyName: '2',
      createTime: '2025-05-19',
      remark: '链接扫描',
    }

    allData.value.push(data1, data2, data3)

  } catch (error) {
    console.error('数据解析失败，重置为默认值:', error)
    allData.value = []
  }
  pagination.total = allData.value.length
}



const saveToStorage = () => {
  try {
    // 存储前再次验证数据类型
    const safeData = Array.isArray(allData.value) ? allData.value : []
    localStorage.setItem(STORAGE_KEY, JSON.stringify(safeData))
    pagination.total = safeData.length
  } catch (error) {
    console.error('数据存储失败:', error)
    ElMessage.error('数据保存失败，请检查控制台')
  }
}
// 新增操作
const handleAdd = () => {
  formData.value = {
    id: Date.now(),
    name: '新链接',
    url: 'https://',
    linkFlag: 'blog',
    status: 1,
    sort: allData.value.length + 1,
    createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    updateTime: ''
  }
  isEdit.value = false
  dialogVisible.value = true
  isButtonShow.value = true
}

// 编辑操作
const handleEdit = (row) => {
  formData.value = { ...row }
  isEdit.value = true
  dialogVisible.value = true
  isButtonShow.value = true
}

// 提交表单
const confirmSubmit = () => {
  if (!formData.value.name || !formData.value.url) {
    ElMessage.error('请填写完整信息')
    return
  }

  if (isEdit.value) {
    const index = allData.value.findIndex(item => item.id === formData.value.id)
    if (index > -1) {
      formData.value.updateTime = new Date().toISOString()
      allData.value.splice(index, 1, formData.value)
    }
  } else {
    allData.value.unshift(formData.value)
  }

  saveToStorage()
  dialogVisible.value = false
  ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
}

// 删除操作
const handleDelete = (id) => {
  allData.value = allData.value.filter(item => item.id !== id)
  saveToStorage()
  ElMessage.success('操作成功')
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
}
</script>

<style scoped>
/* 样式部分保持不变 */
.friend-link-container {
	padding: 20px;
	background: #fff;
	border-radius: 8px;
}

:deep(.el-table .cell) {
	width: max-content;
	display: inline-block;
}

.el-pagination {
	justify-content: flex-end;
	margin-top: 20px;
}
.el-input {
	width: 220px;
}
</style>